package com.darwin.darwinMVC.mvc
{
	import com.darwin.darwinMVC.core.Context;
	import com.darwin.darwinMVC.core.ContextPlace;
	import com.darwin.darwinMVC.core.IListener;
	
	import flash.utils.Dictionary;

	/**
	 * 控制器。用于在视图和数据层之间交互的类
	 * @author lipi
	 */
	public class Controller implements IListener
	{
		public function Controller()
		{
			_context = ContextPlace.getContext();
			_cmdNameDic = new Dictionary();
		}
		
		protected var _context:Context;
		
		/**
		 * 命令字典
		 */
		private var _cmdNameDic:Dictionary;
		
		
		
		/**
		 * 执行命令的方法
		 */
		public function execute(cmd:Command):void
		{
			var cmdName:String = cmd.cmdName;
			var fn:Function = _cmdNameDic[cmdName] as Function;
			fn.call(this,cmd);
		}
		
		
		
		
		/**
		 * 注册一个命令的侦听。注意，一个命令的接收只能使用一个处理函数
		 * @param cmdName 命令名
		 * @param fn 回调函数。函数的参数为命令
		 * @param priority 优先级
		 */
		public function register(cmdName:String,fn:Function,priority:int = 0):void
		{
			_cmdNameDic[cmdName] = fn;
			_context.addCmdListener(cmdName,this,priority);
		}
		
		
		/**
		 * 删除对一个事件的侦听
		 */
		public function removeRegister(cmdName:String):void
		{
			_context.removeCmdListener(cmdName,this);
			delete _cmdNameDic[cmdName];
		}
		
		
		/**
		 * 发布一个数据命令
		 * @param cmd 命令对象
		 */
		public function dispatch(cmd:Command):void
		{
			_context.dispatch(cmd);
		}
		
		
		
		
		public function start():void
		{
			
		}
		
	}
}